package com.lishe.lishe.lishe.module.excitation.activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.annotation.Nullable;
import android.support.v4.view.PagerAdapter;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ClickableSpan;
import android.text.style.URLSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.lishe.lishe.Imageloader.ImageLoaderUtils;
import com.lishe.lishe.R;
import com.lishe.lishe.lishe.MyRecyclerView.TimeLineDecoration;
import com.lishe.lishe.lishe.base.BaseActivity;
import com.lishe.lishe.lishe.bean.OrderObject;
import com.lishe.lishe.lishe.common.Globals;
import com.lishe.lishe.lishe.module.commonclass.WebActivity;
import com.lishe.lishe.lishe.module.excitation.adapter.TimePathAdapter;
import com.lishe.lishe.lishe.module.excitation.bean.WelfareObject;
import com.lishe.lishe.lishe.module.excitation.bean.WelfareOrderObject;
import com.lishe.lishe.lishe.module.excitation.presenter.ExcitationPresenter;
import com.lishe.lishe.lishe.utils.BitmapUtils;
import com.lishe.lishe.lishe.utils.PermissionUtils;
import com.lishe.lishe.lishe.utils.TimeUtils;
import com.lishe.lishe.lishe.utils.UMShareUtils;
import com.lishe.lishe.lishe.utils.Utils;
import com.lishe.lishe.retrofit.BaseDataPageBody;
import com.lishe.lishe.retrofit.DataResponseListener;
import com.lishe.lishe.retrofit.presenter.BaseInfoBody;
import com.lishe.lishe.wxapi.WXEntryActivity;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by shino on 2017/11/23.
 * 福利详情页
 */

public class WelfareDetailsActivity extends BaseActivity implements View.OnClickListener {

    private static final String TAG = WelfareDetailsActivity.class.getSimpleName();
    private Button callBack;
    private TextView title;
    private ImageView giftImage;
    private ImageView integralImage;
    private TextView welfareName;
    private TextView welfareTime;
    private TextView welfareStatus;
    private TextView welfareContent;
    private TextView integral;
    private Button say;
    private Button share;
    private ScrollView scrollView;

    private LinearLayout addressLayout;
    private LinearLayout orderStatusLayout;
    private LinearLayout bottomLayout;
    private TextView welfareAddress;
    private TextView orderstatus;
    private TextView orderdetail;
    private TextView welfareForm;

    private String empId;
    private WelfareObject welfareObject;
    private ImageLoaderUtils imageLoaderUtils;
    private TimePathAdapter adapter;
    private List<WelfareOrderObject> orderObjects = new ArrayList<>();
    private View centeview;


    public static void jump(Activity activity, String empId) {
        Intent intent = new Intent(activity, WelfareDetailsActivity.class);
        intent.putExtra("empId", empId);
        activity.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        imageLoaderUtils = new ImageLoaderUtils();
        empId = getIntent().getStringExtra("empId");
        setContentView(R.layout.activity_welfare_details);
        adapter = new TimePathAdapter(orderObjects);
        initView();

    }

    @Override
    protected void onResume() {
        super.onResume();
        getWelfareInfo();
    }

    private void initView() {
        callBack = findViewById(R.id.title_left_button);
        title = findViewById(R.id.title_text_title);
        title.setText("福利详情");
        centeview = findViewById(R.id.centerview);
        addressLayout = findViewById(R.id.address_layout);
        orderStatusLayout = findViewById(R.id.order_status_layout);
        bottomLayout = findViewById(R.id.bottom_layout);
        giftImage = findViewById(R.id.image);
        integralImage = findViewById(R.id.integral_image);
        welfareName = findViewById(R.id.welfare_name);
        welfareTime = findViewById(R.id.welfare_time);
        welfareStatus = findViewById(R.id.welfare_status);
        welfareContent = findViewById(R.id.welfare_content);
        integral = findViewById(R.id.integral);
        welfareAddress = findViewById(R.id.welfare_address);
        orderstatus = findViewById(R.id.order_status);
        orderdetail = findViewById(R.id.order_detail);
        say = findViewById(R.id.say);
        share = findViewById(R.id.share);
        scrollView = findViewById(R.id.scrollView);
        welfareForm = findViewById(R.id.welfare_form);
        setListener();
    }

    private void initData() {
        if (welfareObject != null) {
            imageLoaderUtils.displayImage(welfareObject.getImgUrl(), giftImage);
            welfareName.setText(welfareObject.getWelfareName());
            welfareTime.setText(TimeUtils.longToyyyyMMdd(welfareObject.getSendTime()));
            welfareStatus.setText(welfareObject.getReceiveFlagToString());
            welfareContent.setText(welfareObject.getWishWord());
            welfareForm.setText(welfareObject.getWelfareFormToString());
            if (welfareObject.getWelfareForm().equals("0")) {//积分福利
                integral.setText(welfareObject.getAmount() + "积分");
                integral.setVisibility(View.VISIBLE);
                integralImage.setVisibility(View.GONE);
                addressLayout.setVisibility(View.GONE);
                orderStatusLayout.setVisibility(View.GONE);
            } else if (welfareObject.getWelfareForm().equals("1")) {//礼包福利
                imageLoaderUtils.displayImage(welfareObject.getPackageImg(), integralImage);
                integral.setVisibility(View.GONE);
                integralImage.setVisibility(View.VISIBLE);
                addressLayout.setVisibility(View.VISIBLE);
                orderStatusLayout.setVisibility(View.VISIBLE);

                String addresStr = "";
                if (!TextUtils.isEmpty(welfareObject.getDistributionTypeToString())) {
                    addresStr = welfareObject.getDistributionTypeToString() + "\n";
                }
                if (!TextUtils.isEmpty(welfareObject.getReceiverAddr())) {
                    addresStr = addresStr + welfareObject.getReceiverAddr() + "\n";
                }
//                if (welfareObject.getReceiveTime() > 0) {
//                    addresStr = addresStr + TimeUtils.longToyyyyMMdd(welfareObject.getReceiveTime()) + "\n";
//                }
                if(!TextUtils.isEmpty(welfareObject.getReceiver())){
                    addresStr=addresStr+welfareObject.getReceiver()+"    ";
                }
                if (!TextUtils.isEmpty(welfareObject.getReceiverPhone())) {
                    addresStr = addresStr + welfareObject.getReceiverPhone() + "\n";
                }
                if (!welfareObject.getReceiveFlag().equals("0")) {
                    welfareAddress.setText(addresStr);
                } else {
                    welfareAddress.setText(welfareObject.getDistributionTypeToString());
                }
                orderstatus.setText(welfareObject.getOrderStatusToString());
            }
            Log.e("对HR说",welfareObject.getFeedback());
            //对HR说按钮处理
            if (!welfareObject.getFeedback().equals("-1")) {//-1：未反馈，0：不满意 1：满意
                say.setVisibility(View.GONE);
            } else {
                if(gettime(welfareObject.getSendTime()) > 15 ){
                    say.setVisibility(View.GONE);
                }else{
                    say.setVisibility(View.VISIBLE);
                }
            }
        }
        setTextViewUrlClick(welfareContent);
    }

    private void setListener() {
        callBack.setOnClickListener(this);
        giftImage.setOnClickListener(this);
        say.setOnClickListener(this);
        share.setOnClickListener(this);
        orderdetail.setOnClickListener(this);
    }

    private long gettime(long sendTime) {
        long time = System.currentTimeMillis();
        long t = (time - sendTime) / (3600 * 1000 * 24);
        Log.e("时间差", t + "");
        return t;
    }

    private void createDialog() {
        final Dialog dialog = new Dialog(this,R.style.MyTransparentDialog);
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_welfare_order_status, null);
        TextView close = view.findViewById(R.id.close);
        RecyclerView recyclerView = view.findViewById(R.id.recyclerview);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        TimeLineDecoration mItemDecoration = new TimeLineDecoration
                .Builder(this)
                .setItemStyle(TimeLineDecoration.STYLE_RESOURCE)//选择dot使用图片资源或者用canvas画
//                .setImageResourse(R.mipmap.time_line_point)
                .setTopDistance(20)//单位dp
                .setItemInterVal(10)//单位dp
                .setItemPaddingLeft(10)//如果不设置，默认和item间距一样
                .setItemPaddingRight(10)//如果不设置，默认和item间距一样
                .setDotColor(R.color.line_da)
                .setDotRadius(4)//单位dp小圆半径
//                .setDotPaddingTop(0)
//                .setDotInItemOrientationCenter(false)//设置dot居中
                .setLineColor(R.color.line_da)//设置线的颜色
                .setLineWidth(1)//单位dp
                .setEndText("END")//设置结束的文字
                .setTextColor(Color.WHITE)
                .setTextSize(10)//单位sp
                .setDotPaddingText(2)//单位dp.设置最后一个点和文字之间的距离
                .setBottomDistance(0)//设置底部距离，可以延长底部线的长度
                .setDotPaddingTop(4)
                .setCicleImageResourse(R.mipmap.time_line_point, 0)
//                .setImageResourse(R.mipmap.point_selected)
                .create();
        recyclerView.addItemDecoration(mItemDecoration);
        recyclerView.setAdapter(adapter);
        close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });

        dialog.addContentView(view, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        dialog.show();

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_left_button:
                finish();
                break;
            case R.id.image://
                if (Globals.getToken() != null) {
                    finish();
                    WebActivity.jump(WelfareDetailsActivity.this, welfareObject.getCardUrl());
                } else {
                    finish();
                    WebActivity.jump(WelfareDetailsActivity.this, welfareObject.getImgUrl());
                }
                break;
            case R.id.say://对HR说
                if (!TextUtils.isEmpty(welfareObject.getHrUrl())) {
                    WebActivity.jump(WelfareDetailsActivity.this, welfareObject.getHrUrl());
                }
                break;
            case R.id.share://分享
                WelfareShareActivity.jump(WelfareDetailsActivity.this, welfareObject);
                break;
            case R.id.order_detail://订单状态详情
                createDialog();
                break;
        }
    }

    private void getWelfareInfo() {
        ExcitationPresenter.getInstance().getWelfareDetail(Globals.getToken(), empId, new DataResponseListener<WelfareObject>() {
            @Override
            public void onSuccess(WelfareObject dataResponse) {
                welfareObject = dataResponse;
                getOrderStatusList();
                initData();
            }

            @Override
            public void onFail(String failMessage) {
                toast(failMessage);
            }

            @Override
            public void onError(Throwable e) {
                toast("网络或服务器异常！");
            }
        });
    }

    /**
     * 或区域订单状态列表
     */
    private void getOrderStatusList() {
        ExcitationPresenter.getInstance().getOrderStatusList(Globals.getToken(), welfareObject.getOrderNo(), new DataResponseListener<BaseDataPageBody>() {
            @Override
            public void onSuccess(BaseDataPageBody dataResponse) {
                Log.e("状态列表", dataResponse.getInfo().size() + "");
                orderObjects.clear();
                orderObjects.addAll(dataResponse.getInfo());
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onFail(String failMessage) {

            }

            @Override
            public void onError(Throwable e) {

            }
        });
    }

    private void setTextViewUrlClick(TextView tv) {
        CharSequence text = tv.getText();
        if (text instanceof Spannable)

        {
            int end = text.length();
            Spannable sp = (Spannable) text;
            URLSpan urls[] = sp.getSpans(0, end, URLSpan.class);
            SpannableStringBuilder style = new SpannableStringBuilder(text);
            style.clearSpans();
            for (URLSpan urlSpan : urls) {
                MyURLSpan myURLSpan = new MyURLSpan(urlSpan.getURL());
                style.setSpan(myURLSpan, sp.getSpanStart(urlSpan),
                        sp.getSpanEnd(urlSpan),
                        Spannable.SPAN_EXCLUSIVE_INCLUSIVE);

            }
            tv.setText(style);
        }
    }

    //TextView的url识别
    private class MyURLSpan extends ClickableSpan {

        private String url;

        public MyURLSpan(String url) {
            this.url = url;
        }

        @Override
        public void onClick(View arg0) {
            WebActivity.jump(WelfareDetailsActivity.this, url);
        }
    }
}
